package com.wangzhen.spring.bean.definition;

import com.wangzhen.spring.ioc.dependcy.entity.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

/**
 * @author dell
 * @since 2020/10/22 12:45
 */
//@Import(AnnotationBeanDefinitionDemo.Config.class)
public class AnnotationBeanDefinitionDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext factory = new AnnotationConfigApplicationContext();
        // 注册配置类
//        factory.register(AnnotationBeanDefinitionDemo.class);
        factory.register(Config.class);

        // 通过BeanDefinitionRegistry手工注册 beanDefinition
        // 1、命名bean的注册方式
        registerBeanDefinition(factory, "registerUser", User.class);
        // 2、非命名bean的注册方式
        registerBeanDefinition2(factory, User.class);

        // 虽然方法名称是refresh，其实相当于启动容器的操作
        factory.refresh();

        // Import导入了一次Config,
        System.out.println("Config类型的所有bean:" + factory.getBeansOfType(Config.class));
        System.out.println("User类型的所有bean:" + factory.getBeansOfType(User.class));

        factory.close();
    }

    /**
     * 命名bean的注册方式
     * @param registry
     * @param beanName
     * @param beanclass
     */
    public static void registerBeanDefinition(BeanDefinitionRegistry registry, String beanName, Class<?> beanclass) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanclass);
        builder.addPropertyValue("age", 10);
        builder.addPropertyValue("name", "zhangsan");
        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        registry.registerBeanDefinition(beanName, beanDefinition);
    }

    /**
     * 非命名bean的注册方式
     * @param registry
     * @param beanclass
     */
    public static void registerBeanDefinition2(BeanDefinitionRegistry registry, Class<?> beanclass) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanclass);
        builder.addPropertyValue("age", 10)
                .addPropertyValue("name", "zhangsan");
        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);
    }

    //@Component
    public static class Config{
        // @Bean注解
        @Bean
        public User user() {
            User user = new User();
            user.setAge(10);
            user.setName("zhangsan");
            return user;
        }
    }

}
